/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Class to set and get Volume or related to it
 * @author libaocheng libaocheng@hisense.com
 * @date 13 June 2013
 */
package com.hisense.settings.sound;

import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import static android.provider.Settings.System.SOUND_EFFECTS_ENABLED;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.preference.SeekBarPreference;
import android.preference.SeekBarDialogPreference;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;

import com.android.settings.R;
import com.android.settings.SoundSettings;
import com.android.settings.VoiceInputOutputSettings;
import com.android.settings.Settings.TextToSpeechSettingsActivity;
import com.hisense.settings.MyLog;
import com.hisense.settings.util.Wrapper;

public class TvSoundSettings extends SoundSettings {
    private static final String TAG = "TvSoundSettings";
    private static final int VALUE_SOUND_MODE_STANDARD = 0;
    private static final String KEY_AUDIO_OUTPUT_MODE = "hdmi_audio_output";
    private static final String KEY_AUDIO_DRC_MODE = "audio_drc";

    private static final String KEY_SOUND_MODE = "sound_mode";
    private static final String KEY_BALANCE = "balance";
    private static final String KEY_SRS = "SRS";
    private static final int VALUE_DYNAMIC_SRS_ON = 1;
    private static final int VALUE_DYNAMIC_SRS_OFF = 0;
    private static final String KEY_USER_EQ = "user_EQ";
    private static final String KEY_TREBLE = "treble";
    private static final String KEY_DIGITAL_AUDIO_OUT = "digital_audio_out";

    //private static String HDMI_CEC_MUTE_UNMUTE_TV_SPEAKER = "com.marvell.hdmicec.SAC_MUTE_UNMUTE_TV_SPEAKER";
    // Internal -> 0
    // External -> 1
    private static final String KEY_TV_SPEEKER = "TV_speeker";
    private static final int VALUE_TV_SPEEKER_ON = 1;
    private static final int VALUE_TV_SPEEKER_OFF = 0;

    // Stand Type -> 0
    // Wall Mount -> 1
    private static final String KEY_SOUND_OPTIMIZER = "sound_optimizer";
    private static final String KEY_AV_SYNC = "AV_sync";
    // set defaul value of AV Sync when option is on
    private static final int VALUE_DEFAULT_AV_SYNC = 3;
    private static final int VALUE_AV_SYNC_ON = 1;
    private static final int VALUE_AV_SYNC_OFF = 0;

    private static final String KEY_SOUND_EFFECTS = "sound_effects";
    private static final int FALLBACK_SOUND_EFFECTS_VALUE = 0;

    private static final String KEY_AUDIO_LANGUAGE = "audio_language";
    private static final String KEY_SAP_MTS = "sap_mts";
    private boolean isTuner = false;
    private boolean isDigitalCh = false;

    private static final String KEY_NOTIFICATION_SOUND = "notification_sound";

    private static final int MSG_UPDATE_RINGTONE_SUMMARY = 1;
    private static final int MSG_UPDATE_NOTIFICATION_SUMMARY = 2;

    private static final String KEY_SOUND_RESET = "sound_reset";
    private static final int DIALOG_SOUND_RESET = 20;

    private static final String KEY_TTS_SETTINGS = "tts_settings";
    private Preference mTtsSettingsPref;

    private int mOldSoundMode;
    private int mOldDigitalSoundOutput;
    private int mOldSoundOptimizer;
    private int mOldAudioLanguage;
    private int mOldSAPMTS;

    private ListPreference mSoundModePreference;
    private SeekBarDialogPreference mBalancePreference;
    private UserEQPreference mUserEQPreference;
    // private SeekBarPreference mBassBoostPreference;
    // private SeekBarPreference mTreblePreference;
    private ListPreference mDigitalAudioOutPreference;
    private ListPreference mSoundOptimizerPreference;
    private ListPreference mAudioLanguagePreference;
    private ListPreference mSAPMTSPreference;
    //    private Preference mRingtonePreference;
    private Preference mNotificationPreference;
    private PreferenceScreen mSoundReset;
    private CheckBoxPreference mSRSCheckBoxPreferenc;
    private static CheckBoxPreference mTVSpeekerCheckBoxPreference;
    private CheckBoxPreference mAVSYNCCheckBoxPreference;

    private OnItemSelectedListener mItemSelectedListener = null;
    private Preference mCurrentPreference = null;
    private AlertDialog mAlertDialog = null;
    private Wrapper mWrapper = null;
    private Context mContext = null;
    private DialogInterface.OnCancelListener mOnCancelListener = null;
    private View.OnClickListener mOnClickListener = null;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_RINGTONE_SUMMARY:
                    //                mRingtonePreference.setSummary((CharSequence) msg.obj);
                    break;
                case MSG_UPDATE_NOTIFICATION_SUMMARY:
                    mNotificationPreference.setSummary((CharSequence) msg.obj);
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mWrapper = Wrapper.getWrapperInstance();
        mWrapper.setContext(mContext);
        //the KEY_AUDIO_OUTPUT_MODE KEY_AUDIO_DRC_MODE used in box
        ListPreference audioOutputModePref = (ListPreference) findPreference(KEY_AUDIO_OUTPUT_MODE);
        ListPreference audioDRCModePref = (ListPreference) findPreference(KEY_AUDIO_DRC_MODE);
        removePreference(KEY_AUDIO_OUTPUT_MODE);
        removePreference(KEY_AUDIO_DRC_MODE);
        mSoundModePreference = (ListPreference) findPreference(KEY_SOUND_MODE);
        // old value
        final int currentSoundMode = getSoundMode();
        mOldSoundMode = currentSoundMode;

        mUserEQPreference = (UserEQPreference) findPreference(KEY_USER_EQ);
        mUserEQPreference.setOnPreferenceChangeListener(this);

        mDigitalAudioOutPreference = (ListPreference) findPreference(KEY_DIGITAL_AUDIO_OUT);
        final int currentDigitalAudioOut = getDigitalAudioOut();
        mOldDigitalSoundOutput = currentDigitalAudioOut;

        mSoundOptimizerPreference = (ListPreference) findPreference(KEY_SOUND_OPTIMIZER);
        final int currentSoundOptimizer = getSoundOptimizer();
        mOldSoundOptimizer = currentSoundOptimizer;

        mAudioLanguagePreference = (ListPreference) findPreference(KEY_AUDIO_LANGUAGE);
        final int currentAudioLanguage = getAudioService();
        mOldAudioLanguage = currentAudioLanguage;

        mSAPMTSPreference = (ListPreference) findPreference(KEY_SAP_MTS);
        final int currentSAPMTS = getMTS();
        mOldSAPMTS = currentSAPMTS;
        // new value
        mSoundModePreference.setValue((String.valueOf(currentSoundMode)));
        mSoundModePreference.setOnPreferenceChangeListener(this);
        //updateSoundModeTitle(currentSoundMode);

        mBalancePreference = (SeekBarDialogPreference) findPreference(KEY_BALANCE);
        mBalancePreference.setOnPreferenceChangeListener(this);
        //updateBlanceTitle();
        mDigitalAudioOutPreference.setValue((String.valueOf(currentDigitalAudioOut)));
        mDigitalAudioOutPreference.setOnPreferenceChangeListener(this);
        //updateDigitalAudioOutTitle(currentDigitalAudioOut);

        mSoundOptimizerPreference.setValue((String.valueOf(currentSoundOptimizer)));
        mSoundOptimizerPreference.setOnPreferenceChangeListener(this);
        //updatemSoundOptimizerTitle(currentSoundOptimizer);

        mAudioLanguagePreference.setValue((String.valueOf(currentAudioLanguage)));
        mAudioLanguagePreference.setOnPreferenceChangeListener(this);
        //updateAudioLanguageTitle(currentAudioLanguage);

        mSAPMTSPreference.setValue((String.valueOf(currentSAPMTS)));
        mSAPMTSPreference.setOnPreferenceChangeListener(this);
        // updateSAPMTSTitle(currentSAPMTS);

        mNotificationPreference = findPreference(KEY_NOTIFICATION_SOUND);

        mSRSCheckBoxPreferenc = (CheckBoxPreference) findPreference(KEY_SRS);
        mTVSpeekerCheckBoxPreference = (CheckBoxPreference) findPreference(KEY_TV_SPEEKER);
        mAVSYNCCheckBoxPreference = (CheckBoxPreference) findPreference(KEY_AV_SYNC);

        mSoundReset = (PreferenceScreen) findPreference(KEY_SOUND_RESET);
        //this can move to onResume
        isTuner = Wrapper.getWrapperInstance().isTunerInput();
        if (isTuner) {
            isDigitalCh = Wrapper.getWrapperInstance().isDigitalChannel();
        }
        // Item of AudioLanguage is enable when source is DTV
        setAuidoLanguageEnable();
        // Item of SAP/MTS is enable when source is ATV
        setSAPMTSEnable();
        // v4 it already exists
        // setupSoundEffects();
        // setupAutoVolume();
        setHDMIARCMute(HdmiARCReceiver.isHDMIARCMute);
        setupSRS();
        setupTVSpeeker();
        setupAVSync();
        isSRSBySoundMode();

        new VoiceInputOutputSettings(this).onCreate();
        mTtsSettingsPref = (Preference) findPreference(KEY_TTS_SETTINGS);
    }

    // add for factory test, start
    // after entering key 1,9,6,9 , then start factory test activity
    private int mHidePassIndex = 0;
    private boolean mHidePassEnable = false;

    private static int[] mHidePass = new int[] { KeyEvent.KEYCODE_1, KeyEvent.KEYCODE_9, KeyEvent.KEYCODE_6, KeyEvent.KEYCODE_9 };

    @Override
    public void onResume() {
        super.onResume();
        updateSoundModeTitle(getSoundMode());
        updateBlanceTitle();
        updateDigitalAudioOutTitle(getDigitalAudioOut());
        updatemSoundOptimizerTitle(getSoundOptimizer());
        updateAudioLanguageTitle(getAudioService());
        updateSAPMTSTitle(getMTS());
        //add factory menu begin
        final PreferenceScreen pfresrn = getPreferenceScreen();
        getListView().setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
                /*MyLog.d(TAG, "position:" + position);
                MyLog.d(TAG, "getListView().getCount():"+ getListView().getCount());
                MyLog.d(TAG, "getListView().:"+ getListView().getItemAtPosition(position).toString());*/
                /**for position start from 0 ,so we will minus 1,and there are 
                 * category also need position so minus 2,that is 3 ,in order to avoid force close
                 * chengbaolee@gmail.com
                 */
                if ((position - 1 < getListView().getCount() - 3) && pfresrn != null 
                                && pfresrn.getPreference((int) position) != null) {

                    if (pfresrn.getPreference((int) position).getKey().equals(KEY_BALANCE)) {
                        mHidePassEnable = true;
                    } else {
                        mHidePassIndex = 0;
                        mHidePassEnable = false;
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });

        getListView().setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    MyLog.d(TAG, "TvSoundSettings on keydown keyCode:" + keyCode);
                    if (mHidePassEnable == true && mHidePassIndex < 4 
                                    && mHidePass[mHidePassIndex++] == keyCode) {
                        MyLog.d(TAG, "TvSoundSettings mHidePassIndex enter:" + mHidePassIndex);
                        if (mHidePassIndex == 4) {
                            try {
                            	Intent intent_factory = new Intent("start.com.hisense.uifac");
                            	getActivity().sendBroadcast(intent_factory);
                                /*Intent intentFactoryMenu = new Intent();
                                ComponentName mFactoryMenuComp = new ComponentName("com.hisense.uifac", "com.hisense.uifac.FacRootMenu");
                                intentFactoryMenu.setComponent(mFactoryMenuComp);
                                intentFactoryMenu.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intentFactoryMenu.setAction("android.intent.action.FACENTRY");
                                getActivity().startActivity(intentFactoryMenu);*/

                            } catch (ActivityNotFoundException e) {
                                Log.w(TAG, e);
                            }
                            exitFromApp();
                            finish();
                            //android.os.Process.killProcess(android.os.Process.myPid());
                            //System.exit(0);
                        }
                    } else {
                        mHidePassIndex = 0;
                        if (mHidePassEnable == true && mHidePass[mHidePassIndex] == keyCode) {
                            mHidePassIndex++;
                        }
                    }

                } else if (event.getAction() == KeyEvent.ACTION_UP) {

                }
                return false;
            }
        });

    }

    public void exitFromApp(){
    	MyLog.d(TAG, "TvSoundSettings closeAppIntente");
    	final Intent closeAppIntent = new Intent("com.hisense.settings.CLOSE_APP");
    	getActivity().sendBroadcast(closeAppIntent);
    }
    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
        Log.d(TAG, "onPreferenceTreeClick->preference" + preference);
        if (preference == mSoundReset) {
            showDialog(DIALOG_SOUND_RESET);
        }

        if (preference == mTtsSettingsPref) {
            Intent ttsintent = new Intent(getActivity(), TextToSpeechSettingsActivity.class);
            startActivity(ttsintent);
        }
        if ((preference != mSoundModePreference) 
                        && (preference != mSoundOptimizerPreference) 
                        && (preference != mAudioLanguagePreference)
                        && (preference != mSAPMTSPreference) 
                        && (preference != mDigitalAudioOutPreference)) {
            return false;
        }
        mCurrentPreference = preference;
        mAlertDialog = (AlertDialog) ((ListPreference) mCurrentPreference).getDialog();
        getItemSelectedListenerInstance();
        getItemOnCancelListenerInstance();
        getItemOnClickListenerInstance();
        if (preference != null) {
            mAlertDialog.getListView().setOnItemSelectedListener(mItemSelectedListener);
            mAlertDialog.setOnCancelListener(mOnCancelListener);
            mAlertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener(mOnClickListener);
        }
        return super.onPreferenceTreeClick(preferenceScreen, preference);
    }

    public boolean onPreferenceChange(Preference preference, Object objValue) {
        final String key = preference.getKey();
        if (KEY_SOUND_MODE.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
                setSoundMode(value);
                mOldSoundMode = value;
                updateSoundModeTitle(value);
                isSRSBySoundMode();
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist sound mode setting", e);
            }
        } else if (KEY_BALANCE.equals(key)) {
            try {
                updateBlanceTitle();
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist balance setting", e);
            }
        } else if (KEY_USER_EQ.equals(key)) {
            try {
                // Sound mode should be Custom after setting User EQ.
                int currentSoundModeTemp = getSoundMode();
                mSoundModePreference.setValue((String.valueOf(currentSoundModeTemp)));
                updateSoundModeTitle(currentSoundModeTemp);
                isSRSBySoundMode();
                Log.d(TAG, "KEY_USER_EQ--->currentSoundModeTemp:" + currentSoundModeTemp);
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist balance setting", e);
            }
        } /*
          * else if (KEY_BASS_BOOST.equals(key)) { try { updateBassBoostTitle();
          * } catch (NumberFormatException e) { Log.e(TAG,
          * "could not persist bass boost setting", e); } } else if
          * (KEY_TREBLE.equals(key)) { try { updateTrebleTitle(); } catch
          * (NumberFormatException e) { Log.e(TAG,
          * "could not persist treble setting", e); } }
          */else if (KEY_DIGITAL_AUDIO_OUT.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
                setDigitalAudioOut(value);
                mOldDigitalSoundOutput = value;
                updateDigitalAudioOutTitle(value);
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist Digital Audio Out setting", e);
            }
        } else if (KEY_SOUND_OPTIMIZER.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
                setSoundOptimizer(value);
                mOldSoundOptimizer = value;
                updatemSoundOptimizerTitle(value);
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist sound optimizer setting", e);
            }
        } else if (KEY_AUDIO_LANGUAGE.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
                setAudioService(value);
                mOldAudioLanguage = value;
                updateAudioLanguageTitle(value);
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist audio language setting", e);
            }
        } else if (KEY_SAP_MTS.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
                setMTS(value);
                mOldSAPMTS = value;
                updateSAPMTSTitle(value);
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist SAP MTS setting", e);
            }
        }
        Log.d(TAG, "onPreferenceChange-->" + preference);
        return true;
    }

    @Override
    public Dialog onCreateDialog(int id) {
        Log.i(TAG, "onCreateDialog = " + id);
        switch (id) {
            case DIALOG_SOUND_RESET: {
                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
                .setTitle(R.string.sound_reset)
                .setMessage(R.string.sound_reset_message)
                .setPositiveButton(R.string.dlg_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        /* User clicked OK so do some stuff */
                        setSoundResset();
                        updateTitleForSoundReset();
                    }
                })
                .setNegativeButton(R.string.dlg_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked Cancel so do some stuff */
                    }
                });

                return builder.create();
            }
            default:
                break;
        }
        return super.onCreateDialog(id);
    }

    // the following method is from wrapper.java used for API
    private int getSoundMode() {
        int value = 0;
        value = Wrapper.getWrapperInstance().getAudioMode();
        MyLog.d(TAG, "getSoundMode--->marvell value:" + value);
        return value;
    }

    private void setSoundMode(int value) {
        Wrapper.getWrapperInstance().setAudioMode(value);
        MyLog.d(TAG, "setSoundMode--->value:" + value);
    }

    private int getSRS() {
        int value = 0;
        value = Wrapper.getWrapperInstance().getSRSStudioSoundHD();
        MyLog.d(TAG, "getSRS = " + value);
        return value;
    }

    private void setSRS(int value) {
        Wrapper.getWrapperInstance().setSRSStudioSoundHD(value);
        MyLog.d(TAG, "setSRS-->value = " + value);
    }

    private int getDigitalAudioOut() {
        int value = 0;
        value = Wrapper.getWrapperInstance().getDigitalAudioOut();
        return value;
    }

    private void setDigitalAudioOut(int value) {
        Wrapper.getWrapperInstance().setDigitalAudioOut(value);
    }

    private int getTVSpeeker() {
        int value = 0;
        value = Wrapper.getWrapperInstance().getTVSpeakers();
        MyLog.d(TAG, "getTVSpeeker = " + value);
        return value;
    }

    private void setTVSpeeker(int value) {
        Wrapper.getWrapperInstance().setTVSpeakers(value);
    }

    private int getSoundOptimizer() {
        int value = 0;
        value = Wrapper.getWrapperInstance().getSoundOptimized();
        return value;
    }

    private void setSoundOptimizer(int value) {
        Wrapper.getWrapperInstance().setSoundOptimized(value);
    }

    private int getAVSync() {
        int value = 0;
        value = Wrapper.getWrapperInstance().getLipSync();
        if (value == 0) {
            value = 0;
        } else {
            value = 1;
        }
        return value;
    }

    private void setAVSync(int value) {
        if (value == 0) {
            value = 0;
        } else {
            value = 3;
        }
        Wrapper.getWrapperInstance().setLipSync(value);
    }

    private int getAudioService() {
        int value = 0;
        value = Wrapper.getWrapperInstance().getAudioService();
        return value;
    }

    private void setAudioService(int value) {
        Wrapper.getWrapperInstance().setAudioService(value);
    }

    private int getMTS() {
        int value = 0;
        value = Wrapper.getWrapperInstance().getMTS();
        return value;
    }

    private void setMTS(int value) {
        Wrapper.getWrapperInstance().setMTS(value);
    }

    private int getBalance() {
        int value = 0;
        value = Wrapper.getWrapperInstance().getBalance();
        return value;
    }

    private void setSoundResset() {
        mWrapper.resetAudioMode(0);
        MyLog.d(TAG, "setSoundResset-->");
    }

    private void updateSoundModeTitle(int value) {
        int updateValue = mSoundModePreference.findIndexOfValue(String.valueOf(value));
        if (updateValue != -1) {
            mSoundModePreference.setTitle(getString(R.string.sound_mode_title).toString() 
                            + ": " + this.getResources().getStringArray(R.array.sound_mode_entries)[updateValue]);
        }
    }

    private void updateBlanceTitle() {
        mBalancePreference.setTitle(getString(R.string.balance_title).toString() + ": " + getBalance());
    }

    private void updateDigitalAudioOutTitle(int value) {
        int updateValue = mDigitalAudioOutPreference.findIndexOfValue(String.valueOf(value));
        if (updateValue != -1) {
            mDigitalAudioOutPreference.setTitle(getString(R.string.Digital_Audio_Out_title).toString() 
                            + ": " + this.getResources().getStringArray(R.array.digital_audio_out_entries)[updateValue]);
        }
    }

    private void updatemSoundOptimizerTitle(int value) {
        int updateValue = mSoundOptimizerPreference.findIndexOfValue(String.valueOf(value));
        if (updateValue != -1) {
            mSoundOptimizerPreference.setTitle(getString(R.string.sound_optimizer_title).toString() 
                            + ": " + this.getResources().getStringArray(R.array.sound_optimizer_entries)[updateValue]);
        }
    }

    private void updateAudioLanguageTitle(int value) {
        int updateValue = mAudioLanguagePreference.findIndexOfValue(String.valueOf(value));
        if (updateValue != -1) {
            mAudioLanguagePreference.setTitle(getString(R.string.audio_language_title).toString() 
                            + ": " + this.getResources().getStringArray(R.array.audio_language_entries)[updateValue]);
        }
    }

    private void updateSAPMTSTitle(int value) {
        int updateValue = mSAPMTSPreference.findIndexOfValue(String.valueOf(value));
        if (updateValue != -1) {
            mSAPMTSPreference.setTitle(getString(R.string.sap_mts_title).toString() 
                            + ": " + this.getResources().getStringArray(R.array.SAP_MTS_entries)[updateValue]);
        }
    }

    private void getItemSelectedListenerInstance() {
        MyLog.d(TAG, "getItemSelectedListenerInstance-->preference:" + mCurrentPreference);
        if (mItemSelectedListener == null) {
            mItemSelectedListener = new OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
                    if (mCurrentPreference == mSoundModePreference) {
                        MyLog.d(TAG, "" + "mSoundModePreference->position:" + position);
                        int CurrentItemValue = Integer.parseInt(getResources().getStringArray(R.array.sound_mode_values)[position]);
                        if (CurrentItemValue != getSoundMode()) {
                            setSoundMode(CurrentItemValue);
                        }
                    } else if (mCurrentPreference == mDigitalAudioOutPreference) {
                        MyLog.d(TAG, "" + "mDigitalAudioOutPreference->position:" + position);
                        int CurrentItemValue = Integer.parseInt(getResources().getStringArray(R.array.digital_audio_out_values)[position]);
                        if (CurrentItemValue != getDigitalAudioOut()) {
                            setDigitalAudioOut(CurrentItemValue);
                        }
                    } else if (mCurrentPreference == mSoundOptimizerPreference) {
                        MyLog.d(TAG, "" + "mSoundOptimizerPreference->position:" + position);
                        int CurrentItemValue = Integer.parseInt(getResources().getStringArray(R.array.sound_optimizer_values)[position]);
                        if (CurrentItemValue != getSoundOptimizer()) {
                            setSoundOptimizer(CurrentItemValue);
                        }
                    } else if (mCurrentPreference == mAudioLanguagePreference) {
                        MyLog.d(TAG, "" + "mAudioLanguagePreference->position:" + position);
                        int CurrentItemValue = Integer.parseInt(getResources().getStringArray(R.array.audio_language_values)[position]);
                        if (CurrentItemValue != getAudioService()) {
                            setAudioService(CurrentItemValue);
                        }
                    } else if (mCurrentPreference == mSAPMTSPreference) {
                        MyLog.d(TAG, "" + "mSAPMTSPreference->position:" + position);
                        int CurrentItemValue = Integer.parseInt(getResources().getStringArray(R.array.SAP_MTS_values)[position]);
                        if (CurrentItemValue != getMTS()) {
                            setMTS(CurrentItemValue);
                        }
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                    MyLog.d(TAG, "onNothingSelected-->arg0:" + arg0);
                }
            };
        }
    }

    private void getItemOnCancelListenerInstance() {
        MyLog.d(TAG, "getItemOnCancelListenerInstance-->preference:" + mCurrentPreference);
        if (mOnCancelListener == null) {
            mOnCancelListener = new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    if (mCurrentPreference == mSoundModePreference) {
                        if (mOldSoundMode != getSoundMode()) {
                            setSoundMode(mOldSoundMode);
                        }
                        MyLog.d(TAG, "onCancel-->mOldSoundMode=" + mOldSoundMode);
                    } else if (mCurrentPreference == mSoundOptimizerPreference) {
                        if (mOldSoundOptimizer != getSoundOptimizer()) {
                            setSoundOptimizer(mOldSoundOptimizer);
                        }
                        MyLog.d(TAG, "onCancel-->mOldSoundOptimizer=" + mOldSoundOptimizer);
                    } else if (mCurrentPreference == mDigitalAudioOutPreference) {
                        if (mOldDigitalSoundOutput != getDigitalAudioOut()) {
                            setDigitalAudioOut(mOldDigitalSoundOutput);
                        }
                        MyLog.d(TAG, "onCancel-->mOldDigitalSoundOutput=" + mOldDigitalSoundOutput);
                    } else if (mCurrentPreference == mAudioLanguagePreference) {
                        if (mOldAudioLanguage != getAudioService()) {
                            setAudioService(mOldAudioLanguage);
                        }
                        MyLog.d(TAG, "onCancel-->mOldAudioLanguage=" + mOldAudioLanguage);
                    } else if (mCurrentPreference == mSAPMTSPreference) {
                        if (mOldSAPMTS != getMTS()) {
                            setMTS(mOldSAPMTS);
                        }
                        MyLog.d(TAG, "onCancel-->mOldSAPMTS=" + mOldSAPMTS);
                    }
                }

            };
        }
    }

    private void getItemOnClickListenerInstance() {
        MyLog.d(TAG, "getItemOnClickListenerInstance-->preference:" + mCurrentPreference);
        if (mOnClickListener == null) {
            mOnClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    if (mCurrentPreference == mSoundModePreference) {
                        if (mOldSoundMode != getSoundMode()) {
                            setSoundMode(mOldSoundMode);
                        }
                        mAlertDialog.dismiss();
                        MyLog.d(TAG, "setOnClickListener-->mOldSoundMode=" + mOldSoundMode);
                    } else if (mCurrentPreference == mSoundOptimizerPreference) {
                        if (mOldSoundOptimizer != getSoundOptimizer()) {
                            setSoundOptimizer(mOldSoundOptimizer);
                        }
                        mAlertDialog.dismiss();
                        MyLog.d(TAG, "setOnClickListener-->mOldSoundOptimizer=" + mOldSoundOptimizer);
                    } else if (mCurrentPreference == mDigitalAudioOutPreference) {
                        if (mOldDigitalSoundOutput != getDigitalAudioOut()) {
                            setDigitalAudioOut(mOldDigitalSoundOutput);
                        }
                        mAlertDialog.dismiss();
                        MyLog.d(TAG, "setOnClickListener-->mOldDigitalSoundOutput=" + mOldDigitalSoundOutput);
                    } else if (mCurrentPreference == mAudioLanguagePreference) {
                        if (mOldAudioLanguage != getAudioService()) {
                            setAudioService(mOldAudioLanguage);
                        }
                        mAlertDialog.dismiss();
                        MyLog.d(TAG, "setOnClickListener-->mOldAudioLanguage=" + mOldAudioLanguage);
                    } else if (mCurrentPreference == mSAPMTSPreference) {
                        if (mOldSAPMTS != getMTS()) {
                            setMTS(mOldSAPMTS);
                        }
                        mAlertDialog.dismiss();
                        MyLog.d(TAG, "setOnClickListener-->mOldSAPMTS=" + mOldSAPMTS);
                    }
                }
            };
        }
    }

    private void setupSoundEffects() {
        final CheckBoxPreference pref = (CheckBoxPreference) findPreference(KEY_SOUND_EFFECTS);
        pref.setPersistent(false);
        int value = Settings.System.getInt(getContentResolver(), SOUND_EFFECTS_ENABLED, FALLBACK_SOUND_EFFECTS_VALUE);
        pref.setChecked(value != 0);
        pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                boolean enabled = pref.isChecked();
                AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                if (enabled) {
                    am.loadSoundEffects();
                } else {
                    am.unloadSoundEffects();
                }
                Settings.System.putInt(getContentResolver(), SOUND_EFFECTS_ENABLED, enabled ? 1 : 0);
                return true;
            }
        });
    }

    private void updateTitleForSoundReset() {

        mOldSoundMode = getSoundMode();
        mOldDigitalSoundOutput = getDigitalAudioOut();
        mOldSoundOptimizer = getSoundOptimizer();
        mOldAudioLanguage = getAudioService();
        mOldSAPMTS = getMTS();
        mItemSelectedListener = null;
        mCurrentPreference = null;
        mAlertDialog = null;
        mOnCancelListener = null;
        mOnClickListener = null;

        int valueUpdate = getSoundMode();
        updateSoundModeTitle(valueUpdate);
        mSoundModePreference.setValue((String.valueOf(valueUpdate)));

        updateBlanceTitle();
        // setupAutoVolume();
        setupSRS();
        isSRSBySoundMode();
        // updateBassBoostTitle();
        // updateTrebleTitle();

        valueUpdate = getDigitalAudioOut();
        updateDigitalAudioOutTitle(valueUpdate);
        mDigitalAudioOutPreference.setValue((String.valueOf(valueUpdate)));

        setupTVSpeeker();

        valueUpdate = getSoundOptimizer();
        updatemSoundOptimizerTitle(valueUpdate);
        mSoundOptimizerPreference.setValue((String.valueOf(valueUpdate)));

        setupAVSync();
        // in v4 it has already done
        // setupSoundEffects();

        valueUpdate = getAudioService();
        updateAudioLanguageTitle(valueUpdate);
        mAudioLanguagePreference.setValue((String.valueOf(valueUpdate)));

        valueUpdate = getMTS();
        updateSAPMTSTitle(valueUpdate);
        mSAPMTSPreference.setValue((String.valueOf(valueUpdate)));

        if (mNotificationPreference != null) {
            updateRingtoneName(RingtoneManager.TYPE_NOTIFICATION, mNotificationPreference, MSG_UPDATE_NOTIFICATION_SUMMARY);
        }
        MyLog.d(TAG, "updateTitleForSoundReset-->");
    }

    private void setupSRS() {
        mSRSCheckBoxPreferenc.setPersistent(false);
        int value = getSRS();
        mSRSCheckBoxPreferenc.setChecked(value != 0);
        mSRSCheckBoxPreferenc.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                boolean enabled = mSRSCheckBoxPreferenc.isChecked();
                if (enabled) {
                    setSRS(VALUE_DYNAMIC_SRS_ON);
                } else {
                    setSRS(VALUE_DYNAMIC_SRS_OFF);
                }
                isSoundModeBySRS();
                return true;
            }
        });
        isSoundModeBySRS();
    }

    private void setupTVSpeeker() {
        mTVSpeekerCheckBoxPreference.setPersistent(false);
        int value = getTVSpeeker();
        mTVSpeekerCheckBoxPreference.setChecked(value != 0);
        mTVSpeekerCheckBoxPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                boolean enabled = mTVSpeekerCheckBoxPreference.isChecked();
                if (enabled) {
                    setTVSpeeker(VALUE_TV_SPEEKER_ON);
                } else {
                    setTVSpeeker(VALUE_TV_SPEEKER_OFF);
                }
                return true;
            }
        });
    }

    private void setupAVSync() {
        mAVSYNCCheckBoxPreference.setPersistent(false);
        int value = getAVSync();
        mAVSYNCCheckBoxPreference.setChecked(value != 0);
        mAVSYNCCheckBoxPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                boolean enabled = mAVSYNCCheckBoxPreference.isChecked();
                if (enabled) {
                    setAVSync(VALUE_AV_SYNC_ON);
                } else {
                    setAVSync(VALUE_AV_SYNC_OFF);
                }
                return true;
            }
        });
    }

    private void setAuidoLanguageEnable() {
        mAudioLanguagePreference.setEnabled(isTuner && isDigitalCh);
    }

    private void setSAPMTSEnable() {
        mSAPMTSPreference.setEnabled(isTuner && !isDigitalCh);
    }

    private void updateRingtoneName(int type, Preference preference, int msg) {
        if (preference == null)
            return;
        Context context = getActivity();
        if (context == null)
            return;
        Uri ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(context, type);
        CharSequence summary = context.getString(com.android.internal.R.string.ringtone_unknown);
        // Is it a silent ringtone?
        if (ringtoneUri == null) {
            summary = context.getString(com.android.internal.R.string.ringtone_silent);
        } else {
            // Fetch the ringtone title from the media provider
            try {
                Cursor cursor = context.getContentResolver()
                                .query(ringtoneUri, new String[] { MediaStore.Audio.Media.TITLE }, null, null, null);
                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        summary = cursor.getString(0);
                    }
                    cursor.close();
                }
            } catch (SQLiteException sqle) {
                // Unknown title for the ringtone
            }
        }
        mHandler.sendMessage(mHandler.obtainMessage(msg, summary));
    }

    private void isSRSBySoundMode() {
        if (getSoundMode() != VALUE_SOUND_MODE_STANDARD) {
            mSRSCheckBoxPreferenc.setEnabled(false);
        } else {
            mSRSCheckBoxPreferenc.setEnabled(true);
        }
    }

    private void isSoundModeBySRS() {
        boolean enabledSRS = mSRSCheckBoxPreferenc.isChecked();
        if (enabledSRS) {
            mSoundModePreference.setEnabled(false);
            mUserEQPreference.setEnabled(false);
        } else {
            mSoundModePreference.setEnabled(true);
            mUserEQPreference.setEnabled(true);
        }
    }

    protected static void setHDMIARCMute(boolean isHDMIARCMuteFlag) {
        Log.i(TAG, "setHDMIARCMute--->" + isHDMIARCMuteFlag);
        if (mTVSpeekerCheckBoxPreference == null) {
            Log.i(TAG, "preference is null!");
            return;
        }

        if (isHDMIARCMuteFlag) {
            mTVSpeekerCheckBoxPreference.setEnabled(false);
        } else {
            mTVSpeekerCheckBoxPreference.setEnabled(true);
        }
    }
}
